﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using InternetShop.Code;

namespace InternetShop
{
    public partial class Content : System.Web.UI.Page
    {
        #region Constants, Fields and Properties

        protected const int PageSize = 10;

        protected Basket basket = new Basket();
        protected IEnumerable<Product> goods;

        protected Basket CurrentBasket
        {
            get
            {
                var b = (Basket)Session["Basket"];
                if (b == null)
                {
                    if (string.IsNullOrEmpty(Context.Profile.UserName))
                        b = new Basket();
                    else
                        b = Basket.LoadForUser(Context.Profile.UserName);
                    Session["Basket"] = b;
                }
                return b;
            }
        }

        protected IEnumerable<Product> Goods
        {
            get {
                if (goods == null)
                {
                    goods = Product.GetProducts().OrderBy(item => item.Price).ToArray();
                }
                return goods;
            }
            set {
                goods = value;
            }
        }

        protected int pageNum { get; set; }

        protected PagedDataSource pSource { get; set; }

        #endregion

        protected string GeneratePath(object obj)
        {
            Product prod = obj as Product;
            return string.IsNullOrEmpty(prod.ImagePath) ? ResolveUrl("~/ContentImages/noImage.jpg") : ResolveUrl("~/ContentImages/" + prod.ImagePath);
        }

        protected bool HasCurrentUserRights()
        {
            return Context.User.IsInRole("Buyers");
        }

        #region Events

        protected void Page_Load(object sender, EventArgs e)
        {
            pageNum = Convert.ToInt32(Request.Params["page"]);
        }

        protected void Page_LoadComplete() 
        {
            pSource = new PagedDataSource();
            pSource.DataSource = Goods;
            pSource.AllowPaging = true;
            pSource.PageSize = PageSize;
            pSource.CurrentPageIndex = pageNum;
            lblCurPage.Text = Convert.ToString(pageNum + 1);
            lblTotal.Text = pSource.PageCount.ToString();
            lbPrev.Visible = !pSource.IsFirstPage;
            lbNext.Visible = !pSource.IsLastPage;
            rItems.DataSource = pSource;
            rItems.DataBind();
        }

        protected void rItems_ItemCommand(object sender, RepeaterCommandEventArgs e)
        {
            Product pr = Goods.ElementAt(e.Item.ItemIndex + (pageNum * PageSize));
            CurrentBasket.AddProduct(pr, 1);
            CurrentBasket.Save();
            Session["Basket"] = CurrentBasket;
            (e.Item.FindControl("lblAdded") as Label).Visible = true;
            (e.Item.FindControl("lbtnAdd") as LinkButton).Visible = false;
        }

        protected void rItems_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            if (!HasCurrentUserRights()) return; // Если нет прав
            if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
            {
                var prod = (Product)e.Item.DataItem;
                if (CurrentBasket.Contains(prod))
                    (e.Item.FindControl("lblAdded") as Label).Visible = true;
                else
                {
                    (e.Item.FindControl("lbtnAdd") as LinkButton).CommandArgument = prod.ID.ToString();
                    (e.Item.FindControl("lbtnAdd") as LinkButton).Visible = true;
                }
            }
        }

        protected void lbtnSortByPrice_Click(object sender, EventArgs e)
        {
            string type = (string)ViewState["SortbyPriceType"];
            if (type == null)
            {
                type = "desc";
                ViewState["SortbyPriceType"] = "asc";
            }
            else
                ViewState["SortbyPriceType"] = "desc";
            if (type == "asc")
            {
                Goods = Goods.OrderBy(item => item.Price).ToArray();
                ViewState["SortbyPriceType"] = "desc";
            }
            else
            {
                Goods = Goods.OrderByDescending(item => item.Price).ToArray();
                ViewState["SortbyPriceType"] = "asc";
            }
            lbtnSortByPrice.CssClass = type;
        }

        protected void lbtnSortByName_Click(object sender, EventArgs e)
        {
            string type = (string)ViewState["SortbyNameType"];
            if (type == null)
            {
                type = "desc";
                ViewState["SortbyNameType"] = "asc";
            }
            else
                ViewState["SortbyNameType"] = "desc";
            if (type == "asc")
            {
                Goods = Goods.OrderBy(item => item.Brand + item.Model).ToArray();
                ViewState["SortbyNameType"] = "desc";
            }
            else
            {
                Goods = Goods.OrderByDescending(item => item.Brand + item.Model).ToArray();
                ViewState["SortbyNameType"] = "asc";
            }
            lbtnSortByName.CssClass = type;
        }

        protected void lbPrev_Click(object sender, EventArgs e)
        {
            Response.Redirect(string.Format("~/Content.aspx?page={0}", pageNum - 1));
        }

        protected void lbNext_Click(object sender, EventArgs e)
        {
            Response.Redirect(string.Format("~/Content.aspx?page={0}", pageNum + 1));
        }

        #endregion
    }
}